// UserPublish 组件的业务逻辑函数

// 导入 HTML 模板
export { render } from './html.js';

// 导入请求工具
import request from '../../../utils/request.js';
import {localStore} from "../../../Store/localStore";

/**
 * 绑定事件监听器
 * @param {UserPublish} component - 组件实例
 */
export function bindEvents(component) {
    const publishModal = component.shadowRoot.getElementById('publishModal');
    const closeBtn = component.shadowRoot.getElementById('closeBtn');
    const publishForm = component.shadowRoot.getElementById('publishForm');
    
    // 表单输入元素
    const titleInput = component.shadowRoot.getElementById('videoTitle');
    const descriptionTextarea = component.shadowRoot.getElementById('videoDescription');
    const tagsInput = component.shadowRoot.getElementById('videoTags');
    const musicNameInput = component.shadowRoot.getElementById('musicName');
    
    // 文件上传区域
    const videoUpload = component.shadowRoot.getElementById('videoUploadArea');
    const coverUpload = component.shadowRoot.getElementById('coverUploadArea');
    const musicUpload = component.shadowRoot.getElementById('musicUploadArea');
    
    // 隐私设置
    const privacyOptions = component.shadowRoot.querySelector('sl-radio-group[name="privacy"]');
    const allowComments = component.shadowRoot.querySelector('sl-checkbox[name="allowComments"]');
    const allowDownload = component.shadowRoot.querySelector('sl-checkbox[name="allowDownload"]');
    
    // 操作按钮
    const draftBtn = component.shadowRoot.getElementById('draftBtn');
    const publishBtn = component.shadowRoot.getElementById('publishBtn');

    // 检查必要元素是否存在
    if (!publishModal || !closeBtn || !publishForm || !titleInput || !descriptionTextarea || !tagsInput || !musicNameInput || !videoUpload || !coverUpload || !musicUpload || !draftBtn || !publishBtn) {
        console.error('UserPublish: 某些必需的DOM元素未找到');
        return;
    }

    // 关闭发布弹窗
    closeBtn.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        closeModal(component);
    });

    // ESC键关闭弹窗
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && component.isOpen) {
            e.preventDefault();
            e.stopPropagation();
            closeModal(component);
        }
    });

    // 表单提交
    publishForm.addEventListener('submit', (e) => {
        e.preventDefault();
        handlePublish(component);
    });

    // 初始化输入字段管理
    initializeInputHandlers(component);

    // 文件上传事件
    setupFileUpload(component, videoUpload, 'video');
    setupFileUpload(component, coverUpload, 'image');
    setupFileUpload(component, musicUpload, 'audio');

    // 草稿保存
    draftBtn.addEventListener('click', () => {
        handleSaveDraft(component);
    });

    // 发布作品
    publishBtn.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        handlePublish(component);
    });

    // 隐私设置变化（如果元素存在）
    if (privacyOptions) {
        privacyOptions.addEventListener('sl-change', () => {
            handlePrivacyChange(component);
        });
    }
}

/**
 * 初始化输入字段处理器
 * @param {UserPublish} component - 组件实例
 */
function initializeInputHandlers(component) {
    // 检查组件是否已经渲染
    if (!component || !component.shadowRoot || !component.shadowRoot.innerHTML.trim()) {
        return;
    }
    
    const inputConfigs = [
        {
            selector: '#videoTitle',
            type: 'title',
            validator: validateTitle,
            charCountId: 'titleCharCount',
            maxLength: 100
        },
        {
            selector: '#videoDescription', 
            type: 'description',
            validator: validateDescription,
            charCountId: 'descCharCount',
            maxLength: 500
        },
        {
            selector: '#videoTags',
            type: 'tags',
            handler: handleTagsInput,
            maxLength: null
        },
        {
            selector: '#musicName',
            type: 'musicName',
            validator: validateMusicName,
            maxLength: 50
        }
    ];

    inputConfigs.forEach(config => {
        const element = component.shadowRoot.querySelector(config.selector);
        if (element) {
            setupInputHandler(component, element, config);
        }
    });
}

/**
 * 设置单个输入字段的处理器
 * @param {UserPublish} component - 组件实例
 * @param {HTMLElement} element - 输入元素
 * @param {Object} config - 配置对象
 */
function setupInputHandler(component, element, config) {
    element.addEventListener('sl-input', () => {
        // 执行验证
        if (config.validator) {
            config.validator(component);
        }
        
        // 执行自定义处理器
        if (config.handler) {
            config.handler(component);
        }
        
        // 更新字符计数
        if (config.charCountId && config.maxLength) {
            updateCharCount(element, config.charCountId, config.maxLength);
        }
        
        // 清除错误状态
        hideFieldError(element);
    });

    // 初始化字符计数
    if (config.charCountId && config.maxLength) {
        updateCharCount(element, config.charCountId, config.maxLength);
    }
}

/**
 * 设置文件上传功能
 * @param {UserPublish} component - 组件实例
 * @param {HTMLElement} uploadArea - 上传区域元素
 * @param {string} fileType - 文件类型 (video/image/audio)
 */
function setupFileUpload(component, uploadArea, fileType) {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.style.display = 'none';
    
    // 设置文件类型限制
    switch (fileType) {
        case 'video':
            fileInput.accept = 'video/*';
            break;
        case 'image':
            fileInput.accept = 'image/*';
            break;
        case 'audio':
            fileInput.accept = 'audio/*';
            break;
    }
    
    uploadArea.appendChild(fileInput);

    // 点击上传区域触发文件选择
    uploadArea.addEventListener('click', (e) => {
        if (!e.target.closest('.remove-file, .remove-image, .remove-music')) {
            fileInput.click();
        }
    });

    // 文件选择事件
    fileInput.addEventListener('change', (e) => {
        const files = e.target.files;
        if (files.length > 0) {
            handleFileSelect(component, files[0], fileType, uploadArea);
        }
    });

    // 拖拽事件
    setupDragAndDrop(component, uploadArea, fileType);
}

/**
 * 设置拖拽上传功能
 * @param {UserPublish} component - 组件实例
 * @param {HTMLElement} uploadArea - 上传区域元素
 * @param {string} fileType - 文件类型
 */
function setupDragAndDrop(component, uploadArea, fileType) {
    // 防止默认拖拽行为
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
    });

    // 拖拽进入和悬停
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, () => {
            uploadArea.classList.add('drag-over');
        }, false);
    });

    // 拖拽离开
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, () => {
            uploadArea.classList.remove('drag-over');
        }, false);
    });

    // 文件放置
    uploadArea.addEventListener('drop', (e) => {
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelect(component, files[0], fileType, uploadArea);
        }
    }, false);
}

/**
 * 防止默认拖拽行为
 * @param {Event} e - 事件对象
 */
function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

/**
 * 处理文件选择
 * @param {UserPublish} component - 组件实例
 * @param {File} file - 选择的文件
 * @param {string} fileType - 文件类型
 * @param {HTMLElement} uploadArea - 上传区域元素
 */
function handleFileSelect(component, file, fileType, uploadArea) {
    // 验证文件类型和大小
    if (!validateFile(file, fileType)) {
        return;
    }

    // 存储文件到组件状态
    if (!component.files) {
        component.files = {};
    }
    component.files[fileType] = file;

    // 显示文件预览
    showFilePreview(component, file, fileType, uploadArea);

    // 触发验证
    validateFiles(component);
}

/**
 * 验证文件
 * @param {File} file - 文件对象
 * @param {string} fileType - 文件类型
 * @returns {boolean} 验证结果
 */
function validateFile(file, fileType) {
    const maxSizes = {
        video: 500 * 1024 * 1024, // 500MB
        image: 10 * 1024 * 1024,  // 10MB
        audio: 50 * 1024 * 1024   // 50MB
    };

    const allowedTypes = {
        video: ['video/mp4', 'video/webm', 'video/ogg', 'video/avi', 'video/mov'],
        image: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'],
        audio: ['audio/mp3', 'audio/wav', 'audio/ogg', 'audio/aac', 'audio/m4a']
    };

    // 检查文件大小
    if (file.size > maxSizes[fileType]) {
        showError(`文件大小不能超过 ${Math.round(maxSizes[fileType] / 1024 / 1024)}MB`);
        return false;
    }

    // 检查文件类型
    if (!allowedTypes[fileType].includes(file.type)) {
        showError(`不支持的${fileType === 'video' ? '视频' : fileType === 'image' ? '图片' : '音频'}格式`);
        return false;
    }

    return true;
}

/**
 * 显示文件预览
 * @param {UserPublish} component - 组件实例
 * @param {File} file - 文件对象
 * @param {string} fileType - 文件类型
 * @param {HTMLElement} uploadArea - 上传区域元素
 */
function showFilePreview(component, file, fileType, uploadArea) {
    const reader = new FileReader();
    
    reader.onload = (e) => {
        let previewHTML = '';
        
        switch (fileType) {
            case 'video':
                previewHTML = `
                    <div class="file-preview">
                        <sl-icon name="play-circle" style="font-size: 2rem; color: #60a5fa;"></sl-icon>
                        <span class="file-name">${file.name}</span>
                        <sl-icon-button name="x-circle" class="remove-file" title="移除视频"></sl-icon-button>
                    </div>
                `;
                break;
            case 'image':
                previewHTML = `
                    <div class="image-preview">
                        <img src="${e.target.result}" alt="封面预览" class="preview-image">
                        <span class="file-name">${file.name}</span>
                        <sl-icon-button name="x-circle" class="remove-image" title="移除图片"></sl-icon-button>
                    </div>
                `;
                break;
            case 'audio':
                previewHTML = `
                    <div class="music-preview">
                        <sl-icon name="music-note" style="font-size: 2rem; color: #60a5fa;"></sl-icon>
                        <div class="music-info">
                            <span class="music-file-name">${file.name}</span>
                            <span class="music-duration">正在获取时长...</span>
                        </div>
                        <sl-icon-button name="x-circle" class="remove-music" title="移除音乐"></sl-icon-button>
                    </div>
                `;
                break;
        }
        
        uploadArea.innerHTML = previewHTML;
        
        // 绑定移除文件事件
        const removeBtn = uploadArea.querySelector(`.remove-${fileType === 'image' ? 'image' : fileType === 'audio' ? 'music' : 'file'}`);
        if (removeBtn) {
            removeBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                removeFile(component, fileType, uploadArea);
            });
        }

        // 如果是音频文件，获取时长
        if (fileType === 'audio') {
            getAudioDuration(file).then(duration => {
                const durationElement = uploadArea.querySelector('.music-duration');
                if (durationElement) {
                    durationElement.textContent = formatDuration(duration);
                }
            });
        }
    };
    
    if (fileType === 'image') {
        reader.readAsDataURL(file);
    } else {
        reader.onload();
    }
}

/**
 * 移除文件
 * @param {UserPublish} component - 组件实例
 * @param {string} fileType - 文件类型
 * @param {HTMLElement} uploadArea - 上传区域元素
 */
function removeFile(component, fileType, uploadArea) {
    // 从组件状态中移除文件
    if (component.files && component.files[fileType]) {
        delete component.files[fileType];
    }

    // 恢复上传区域的原始状态
    const originalHTML = {
        video: `
            <sl-icon name="cloud-upload" class="upload-icon"></sl-icon>
            <p class="upload-text">拖拽视频文件到此处，或点击选择</p>
            <p class="upload-hint">支持 MP4、WebM、AVI 等格式，最大 500MB</p>
        `,
        image: `
            <sl-icon name="image" class="upload-icon"></sl-icon>
            <p class="upload-text">拖拽封面图片到此处，或点击选择</p>
            <p class="upload-hint">支持 JPG、PNG、GIF 等格式，最大 10MB</p>
        `,
        audio: `
            <sl-icon name="music-note" class="upload-icon"></sl-icon>
            <p class="upload-text">拖拽音乐文件到此处，或点击选择</p>
            <p class="upload-hint">支持 MP3、WAV、AAC 等格式，最大 50MB</p>
        `
    };

    uploadArea.innerHTML = originalHTML[fileType];
    
    // 重新设置文件上传功能
    setupFileUpload(component, uploadArea, fileType);
    
    // 触发验证
    validateFiles(component);
}

/**
 * 获取音频时长
 * @param {File} file - 音频文件
 * @returns {Promise<number>} 音频时长（秒）
 */
function getAudioDuration(file) {
    return new Promise((resolve) => {
        const audio = new Audio();
        audio.addEventListener('loadedmetadata', () => {
            resolve(audio.duration);
        });
        audio.addEventListener('error', () => {
            resolve(0);
        });
        audio.src = URL.createObjectURL(file);
    });
}

/**
 * 格式化时长
 * @param {number} seconds - 秒数
 * @returns {string} 格式化的时长字符串
 */
function formatDuration(seconds) {
    if (!seconds || seconds === 0) return '未知时长';
    
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}

/**
 * 处理标签输入
 * @param {UserPublish} component - 组件实例
 */
function handleTagsInput(component) {
    const tagsInput = component.shadowRoot.getElementById('workTags');
    const tagsPreview = component.shadowRoot.querySelector('.tags-preview');
    
    if (!tagsInput || !tagsPreview) return;
    
    const value = tagsInput.value.trim();
    if (!value) {
        tagsPreview.innerHTML = '';
        return;
    }
    
    // 分割标签（支持逗号、空格、换行分割）
    const tags = value.split(/[,\s\n]+/).filter(tag => tag.trim().length > 0);
    
    // 限制标签数量
    const maxTags = 10;
    const limitedTags = tags.slice(0, maxTags);
    
    // 生成标签预览
    const tagsHTML = limitedTags.map(tag => 
        `<span class="tag-item">#${tag.trim()}</span>`
    ).join('');
    
    tagsPreview.innerHTML = tagsHTML;
    
    // 如果超出限制，显示提示
    if (tags.length > maxTags) {
        showError(`最多只能添加 ${maxTags} 个标签`);
    }
}

/**
 * 更新字符计数
 * @param {HTMLElement} input - 输入元素
 * @param {string} counterId - 计数器元素ID
 * @param {number} maxLength - 最大长度
 */
function updateCharCount(input, counterId, maxLength) {
    const component = input.closest('user-publish');
    if (!component || !component.shadowRoot) {
        return;
    }
    const counterElement = component.shadowRoot.getElementById(counterId);
    
    if (counterElement) {
        const current = input.value.length;
        counterElement.textContent = current;
        
        // 获取字符计数容器
        const charCountContainer = counterElement.closest('.char-count');
        if (charCountContainer) {
            // 根据字符数量改变颜色
            if (current > maxLength * 0.9) {
                charCountContainer.style.color = '#fca5a5';
                charCountContainer.style.background = 'rgba(239, 68, 68, 0.1)';
            } else if (current > maxLength * 0.7) {
                charCountContainer.style.color = '#fbbf24';
                charCountContainer.style.background = 'rgba(245, 158, 11, 0.1)';
            } else {
                charCountContainer.style.color = 'rgba(255, 255, 255, 0.7)';
                charCountContainer.style.background = 'rgba(255, 255, 255, 0.05)';
            }
        }
    }
}

/**
 * 打开模态框
 * @param {UserPublish} component - 组件实例
 */
export function openModal(component) {
    component.isOpen = true;
    const modal = component.shadowRoot.getElementById('publishModal');
    modal.classList.add('show');
    
    // 聚焦到标题输入框
    setTimeout(() => {
        const titleInput = component.shadowRoot.getElementById('videoTitle');
        if (titleInput) {
            titleInput.focus();
        }
    }, 300);

    // 触发自定义事件
    component.dispatchEvent(new CustomEvent('modal-opened', {
        bubbles: true,
        detail: { component: 'user-publish' }
    }));
}

/**
 * 关闭模态框
 * @param {UserPublish} component - 组件实例
 */
export function closeModal(component) {
    // 强制关闭，不进行任何确认
    component.isOpen = false;
    const modal = component.shadowRoot.getElementById('publishModal');
    if (modal) {
        modal.classList.remove('show');
    }
    
    // 清除错误信息
    clearErrors(component);
    
    // 重置表单
    resetForm(component);

    // 触发自定义事件
    component.dispatchEvent(new CustomEvent('modal-closed', {
        bubbles: true,
        detail: { component: 'user-publish' }
    }));
}

/**
 * 处理发布作品
 * @param {UserPublish} component - 组件实例
 */
export async function handlePublish(component) {
    // 防止重复调用
    if (component.isPublishing) {
        console.log('Debug - Already publishing, skipping...');
        return;
    }
    component.isPublishing = true;

    const videoTitle = component.shadowRoot.querySelector('#videoTitle');
    const videoFile = component.shadowRoot.querySelector('#videoFile');
    const videoDescription = component.shadowRoot.querySelector('#videoDescription');

    // 检查必要的元素是否存在
    if (!videoTitle || !videoFile || !videoDescription) {
        console.error('Required form elements not found');
        showError('表单元素未找到，请刷新页面重试');
        component.isPublishing = false;
        return;
    }

    // 检查组件中是否有视频文件
    const hasVideoFile = component.files && component.files.video;
    
    console.log('Publishing video:', hasVideoFile ? component.files.video.name : 'No file selected');

    // 检查是否有文件被选择（从组件状态中获取）
    if (!hasVideoFile) {
        showError('请先选择要上传的视频文件');
        component.isPublishing = false;
        return;
    }

    try {
        // 前端切片
        const file = component.files.video;
        const chunkSize = 1 * 1024 * 1024; // 1MB
        const chunkNumber = Math.ceil(file.size / chunkSize);
        const chunks = [];

        // 生成所有切片
        for (let i = 0; i < chunkNumber; i++) {
            const start = i * chunkSize;
            const end = (i + 1) * chunkSize;
            chunks.push(file.slice(start, end));
        }

        console.log(`开始上传文件切片，共 ${chunkNumber} 个切片`);

        // 获取已上传的切片索引（断点续传）
        const uploadedIndex = parseInt(localStore.get(`${file.size}-${file.name}`)) || 0;
        const remainingChunks = chunks.slice(uploadedIndex);
        
        if (remainingChunks.length === 0) {
            console.log('所有切片已上传完成，直接进行合并');
        } else {
            // 显示上传进度
            updateUploadProgress(component, uploadedIndex, chunkNumber);
            
            // 创建上传任务数组，限制并发数量避免服务器压力过大
            const maxConcurrency = 3; // 最大并发数
            const uploadResults = [];
            
            console.log(`开始并发上传 ${remainingChunks.length} 个切片，最大并发数: ${maxConcurrency}`);
            
            // 分批并发上传
            for (let i = 0; i < remainingChunks.length; i += maxConcurrency) {
                const batch = remainingChunks.slice(i, i + maxConcurrency);
                const batchTasks = batch.map((chunk, batchIndex) => {
                    const actualIndex = uploadedIndex + i + batchIndex;
                    return uploadChunkWithRetry(chunk, actualIndex, chunkNumber, file.name, 3);
                });

                try {
                    const batchResults = await Promise.all(batchTasks);
                    
                    // 处理批次结果
                    batchResults.forEach((result, batchIndex) => {
                        const actualIndex = uploadedIndex + i + batchIndex;
                        if (result.success) {
                            localStore.set(`${file.size}-${file.name}`, actualIndex + 1);
                            console.log(`切片 ${actualIndex + 1}/${chunkNumber} 上传成功`);
                            
                            // 更新进度
                            updateUploadProgress(component, actualIndex + 1, chunkNumber);
                        } else {
                            throw new Error(`切片 ${actualIndex + 1} 上传失败: ${result.error}`);
                        }
                    });
                    
                    uploadResults.push(...batchResults);
                } catch (error) {
                    console.error('批次上传失败:', error);
                    throw error;
                }
            }

            console.log('所有文件切片上传完成！');
        }

        // 发出合并请求
        const mergeData = {
            fromid: 1,
            title: videoTitle.value,
            isduet: 1,
            type: "shortVideo",
            desc: videoDescription.value || "随便写点啥",
            filename: file.name,
            total: chunkNumber,
        };

        const formData = new FormData();
        Object.keys(mergeData).forEach((key) => {
            formData.append(key, mergeData[key]);
        });

        console.log('开始合并文件切片...');
        const mergeResponse = await request.post("/content/videos/merge-chunk", formData);

        if (mergeResponse.data.code === 0) {
            // 上传成功，清除本地存储的断点续传信息
            localStore.remove(`${file.size}-${file.name}`);

            alert(mergeResponse.data.message || mergeResponse.data.msg || '上传成功！');
            
            // 移除发布组件
            const userPublish = document.querySelector('user-publish');
            userPublish?.remove();
        } else {
            throw new Error(mergeResponse.data.message || '文件合并失败');
        }

    } catch (error) {
        console.error('视频发布失败:', error);
        showError(`发布失败: ${error.message}`);
    } finally {
        // 重置发布状态
        component.isPublishing = false;
    }
}

/**
 * 更新上传进度显示
 * @param {UserPublish} component - 组件实例
 * @param {number} uploaded - 已上传切片数
 * @param {number} total - 总切片数
 */
function updateUploadProgress(component, uploaded, total) {
    const percentage = Math.round((uploaded / total) * 100);
    console.log(`上传进度: ${uploaded}/${total} (${percentage}%)`);
    
    // 可以在这里添加UI进度条更新逻辑
    // 例如：更新组件中的进度条元素
    const progressElement = component.shadowRoot.querySelector('.upload-progress');
    if (progressElement) {
        progressElement.textContent = `上传进度: ${percentage}%`;
        progressElement.style.width = `${percentage}%`;
    }
}

/**
 * 带重试机制的上传切片
 * @param {Blob} chunk - 文件切片
 * @param {number} index - 切片索引
 * @param {number} total - 总切片数
 * @param {string} filename - 文件名
 * @param {number} maxRetries - 最大重试次数
 * @returns {Promise<{success: boolean, error?: string}>}
 */
async function uploadChunkWithRetry(chunk, index, total, filename, maxRetries = 3) {
    let lastError = null;
    
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            const result = await uploadChunk(chunk, index, total, filename);
            
            if (result.success) {
                return result;
            } else {
                lastError = result.error;
                if (attempt < maxRetries) {
                    console.warn(`切片 ${index + 1} 第 ${attempt} 次上传失败，准备重试: ${result.error}`);
                    // 指数退避延迟
                    await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
                }
            }
        } catch (error) {
            lastError = error.message || '网络错误';
            if (attempt < maxRetries) {
                console.warn(`切片 ${index + 1} 第 ${attempt} 次上传异常，准备重试: ${lastError}`);
                await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
            }
        }
    }
    
    return { success: false, error: `重试 ${maxRetries} 次后仍然失败: ${lastError}` };
}

/**
 * 上传单个切片
 * @param {Blob} chunk - 文件切片
 * @param {number} index - 切片索引
 * @param {number} total - 总切片数
 * @param {string} filename - 文件名
 * @returns {Promise<{success: boolean, error?: string}>}
 */
async function uploadChunk(chunk, index, total, filename) {
    const formData = new FormData();
    formData.append('fromid', 1);
    formData.append('nowNum', index + 1);
    formData.append('total', total);
    formData.append('video', chunk);
    formData.append('filename', filename);

    try {
        const response = await request.post("/content/videos/upload-chunk", formData);
        
        if (response.data.code === 0) {
            return { success: true };
        } else {
            return { success: false, error: response.data.msg || '上传失败' };
        }
    } catch (error) {
        return { success: false, error: error.message || '网络错误' };
    }
}

/**
 * 处理保存草稿
 * @param {UserPublish} component - 组件实例
 */
export async function handleSaveDraft(component) {
    setLoading(component, true);

    try {
        const formData = collectFormData(component);
        formData.isDraft = true;
        
        const result = await performPublish(formData);
        
        if (result.success) {
            showSuccess('草稿保存成功');
            closeModal(component);
        } else {
            showError(result.message || '保存草稿失败');
        }
    } catch (error) {
        console.error('保存草稿失败:', error);
        showError('保存草稿失败，请稍后重试');
    } finally {
        setLoading(component, false);
    }
}

/**
 * 收集表单数据
 * @param {UserPublish} component - 组件实例
 * @returns {FormData} 表单数据
 */
function collectFormData(component) {
    const formData = new FormData();
    
    // 基本信息
    const titleElement = component.shadowRoot.getElementById('videoTitle');
    const descriptionElement = component.shadowRoot.getElementById('videoDescription');
    const tagsElement = component.shadowRoot.getElementById('videoTags');
    const musicNameElement = component.shadowRoot.getElementById('musicName');
    
    const title = titleElement?.value || '';
    const description = descriptionElement?.value || '';
    const tags = tagsElement?.value || '';
    const musicName = musicNameElement?.value || '';
    
    formData.append('title', title);
    formData.append('description', description);
    formData.append('tags', tags);
    formData.append('musicName', musicName);
    
    // 隐私设置
    const privacyGroup = component.shadowRoot.querySelector('sl-radio-group[name="privacy"]');
    const privacy = privacyGroup?.value || 'public';
    const allowComments = component.shadowRoot.querySelector('sl-checkbox[name="allowComments"]')?.checked || false;
    const allowDownload = component.shadowRoot.querySelector('sl-checkbox[name="allowDownload"]')?.checked || false;
    
    formData.append('privacy', privacy);
    formData.append('allowComments', allowComments);
    formData.append('allowDownload', allowDownload);
    
    // 文件
    if (component.files) {
        if (component.files.video) {
            formData.append('video', component.files.video);
        }
        if (component.files.image) {
            formData.append('cover', component.files.image);
        }
        if (component.files.audio) {
            formData.append('music', component.files.audio);
        }
    }
    
    return formData;
}

/**
 * 执行发布请求
 * @param {FormData} formData - 表单数据
 * @returns {Promise<Object>} 发布结果
 */
async function performPublish(formData) {
    // 模拟发布请求
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                success: true,
                data: {
                    id: Date.now(),
                    title: formData.get('title'),
                    status: formData.get('isDraft') ? 'draft' : 'published'
                }
            });
        }, 2000);
    });
}

/**
 * 处理发布成功
 * @param {UserPublish} component - 组件实例
 * @param {Object} data - 返回数据
 */
function handlePublishSuccess(component, data) {
    showSuccess('作品发布成功！');
    closeModal(component);
    
    // 触发发布成功事件
    component.dispatchEvent(new CustomEvent('publish-success', {
        bubbles: true,
        detail: data
    }));
}

/**
 * 处理发布错误
 * @param {UserPublish} component - 组件实例
 * @param {string} message - 错误信息
 */
function handlePublishError(component, message) {
    showError(message);
}

/**
 * 处理隐私设置变化
 * @param {UserPublish} component - 组件实例
 */
function handlePrivacyChange(component) {
    const selectedRadio = component.shadowRoot.querySelector('sl-radio[checked]');
    if (selectedRadio) {
        console.log('隐私设置已更改为:', selectedRadio.value);
    }
}

/**
 * 表单验证
 * @param {UserPublish} component - 组件实例
 * @returns {boolean} 验证结果
 */
function validateForm(component) {
    let isValid = true;
    
    isValid = validateTitle(component) && isValid;
    isValid = validateDescription(component) && isValid;
    isValid = validateFiles(component) && isValid;
    
    return isValid;
}

/**
 * 验证标题
 * @param {UserPublish} component - 组件实例
 * @returns {boolean} 验证结果
 */
function validateTitle(component) {
    const titleInput = component.shadowRoot.getElementById('videoTitle');
    const title = titleInput.value.trim();
    
    if (!title) {
        showFieldError(titleInput, '请输入作品标题');
        return false;
    }
    
    if (title.length < 2) {
        showFieldError(titleInput, '标题至少需要2个字符');
        return false;
    }
    
    if (title.length > 100) {
        showFieldError(titleInput, '标题不能超过100个字符');
        return false;
    }
    
    hideFieldError(titleInput);
    return true;
}

/**
 * 验证描述
 * @param {UserPublish} component - 组件实例
 * @returns {boolean} 验证结果
 */
function validateDescription(component) {
    const descriptionTextarea = component.shadowRoot.getElementById('videoDescription');
    const description = descriptionTextarea.value.trim();
    
    if (description.length > 1000) {
        showFieldError(descriptionTextarea, '描述不能超过1000个字符');
        return false;
    }
    
    hideFieldError(descriptionTextarea);
    return true;
}

/**
 * 验证音乐名称
 * @param {UserPublish} component - 组件实例
 * @returns {boolean} 验证结果
 */
function validateMusicName(component) {
    const musicNameInput = component.shadowRoot.getElementById('musicName');
    const musicName = musicNameInput.value.trim();
    
    if (musicName.length > 100) {
        showFieldError(musicNameInput, '音乐名称不能超过100个字符');
        return false;
    }
    
    hideFieldError(musicNameInput);
    return true;
}

/**
 * 验证文件
 * @param {UserPublish} component - 组件实例
 * @returns {boolean} 验证结果
 */
function validateFiles(component) {
    if (!component.files || !component.files.video) {
        showError('请上传视频文件');
        return false;
    }
    
    return true;
}

/**
 * 显示字段错误
 * @param {HTMLElement} field - 字段元素
 * @param {string} message - 错误信息
 */
function showFieldError(field, message) {
    const errorElement = field.closest('.form-group').querySelector('.error-message');
    if (errorElement) {
        errorElement.textContent = message;
        errorElement.classList.add('show');
    }
}

/**
 * 隐藏字段错误
 * @param {HTMLElement} field - 字段元素
 */
function hideFieldError(field) {
    const errorElement = field.closest('.form-group').querySelector('.error-message');
    if (errorElement) {
        errorElement.classList.remove('show');
    }
}

/**
 * 显示错误信息
 * @param {string} message - 错误信息
 */
function showError(message) {
    // 这里可以使用 MessageToast 组件显示错误
    console.error(message);
    // alert(message); // 临时使用 alert，实际项目中应该使用更好的提示组件
}

/**
 * 显示成功信息
 * @param {string} message - 成功信息
 */
function showSuccess(message) {
    // 这里可以使用 MessageToast 组件显示成功信息
    console.log(message);
    alert(message); // 临时使用 alert，实际项目中应该使用更好的提示组件
}

/**
 * 清除所有错误信息
 * @param {UserPublish} component - 组件实例
 */
function clearErrors(component) {
    const errorElements = component.shadowRoot.querySelectorAll('.error-message');
    errorElements.forEach(element => {
        element.classList.remove('show');
    });
}

/**
 * 重置表单
 * @param {UserPublish} component - 组件实例
 */
function resetForm(component) {
    const form = component.shadowRoot.getElementById('publishForm');
    if (form) {
        form.reset();
    }
    
    // 清除文件
    component.files = {};
    
    // 重置上传区域
    const uploadAreas = component.shadowRoot.querySelectorAll('.upload-area');
    uploadAreas.forEach((area, index) => {
        const fileTypes = ['video', 'image', 'audio'];
        const fileType = fileTypes[index];
        if (fileType) {
            removeFile(component, fileType, area);
        }
    });
    
    // 清除标签预览
    const tagsPreview = component.shadowRoot.querySelector('.tags-preview');
    if (tagsPreview) {
        tagsPreview.innerHTML = '';
    }
    
    // 重置字符计数
    const charCounts = component.shadowRoot.querySelectorAll('.char-count');
    charCounts.forEach(counter => {
        counter.textContent = '0/0';
        counter.style.color = 'rgba(255, 255, 255, 0.5)';
    });
}

/**
 * 设置加载状态
 * @param {UserPublish} component - 组件实例
 * @param {boolean} loading - 是否加载中
 */
function setLoading(component, loading) {
    component.isLoading = loading;
    const publishBtn = component.shadowRoot.getElementById('publishBtn');
    const draftBtn = component.shadowRoot.getElementById('draftBtn');
    
    if (loading) {
        publishBtn.loading = true;
        draftBtn.disabled = true;
        component.shadowRoot.querySelector('.publish-form-container').classList.add('loading');
    } else {
        publishBtn.loading = false;
        draftBtn.disabled = false;
        component.shadowRoot.querySelector('.publish-form-container').classList.remove('loading');
    }
}